<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
					<jk-button :has-permission="getPermission([`${prefix}:export`])" :disabled="recordIds.length === 0" class="margin-5-0 item-gap" type="warning" @click="onReportBtn">导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.serviceState" :option-list="overStateList" placeholder="是否完成" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" size="small" type="daterange" style="width: 280px;" value-format="yyyy-MM-dd" placeholder="选择日期" class="search-bar-item-size1 item-gap"></jk-date-picker>
					<jk-search-input v-model="searchParams.workshopBatchCode" placeholder="厂批" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.primaryBatchCode" placeholder="原批" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				show-footer
				:footer-method="footerMethod"
				:height="tableHeight + 10"
				:checkbox-config="{checkMethod: checkboxMethod}"
				@checkbox-change="onCheckBoxChange"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else-if="item.keyName === 'ifHaveCotton'">
							<jk-state-bar :state="scope.row.ifHaveCotton === false ? 0 : 1" :state-list="overStateList"></jk-state-bar>
						</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="350">
					<template slot-scope="scope">
						<div class="flex-center">
							<div class="flex-center">
								<jk-button v-if="scope.row.serviceState === 0" :has-permission="getPermission([`${prefix}:state`])" class="item-gap" icon="el-icon-s-promotion" size="mini" type="success" @click="onItemServiceState(scope.row.id)">已完成</jk-button>
								<jk-button v-if="scope.row.serviceState === 1" :has-permission="getPermission([`${prefix}:state`])" class="item-gap" icon="el-icon-s-promotion" size="mini" type="warning" @click="onItemRevocationServiceState(scope.row.id)">撤销完成</jk-button>
								<jk-button v-if="scope.row.auditState === 0" :has-permission="getPermission([`${prefix}:state`])" class="item-gap" icon="el-icon-s-promotion" size="mini" type="success" @click="onItemState(scope.row.id)">审核</jk-button>
								<jk-button v-if="scope.row.auditState === 1" :has-permission="getPermission([`${prefix}:state`])" class="item-gap" icon="el-icon-s-promotion" size="mini" type="warning" @click="onItemRevocationState(scope.row.id)">撤销</jk-button>
								<jk-button
									class="item-gap"
									:prefix="prefix"
									icon="el-icon-edit"
									:has-permission="getPermission([`${prefix}:update`])"
									size="mini"
									:disabled="scope.row.auditState !== 0"
									type="primary"
									@click="onEditBtn(scope.row.id)"
								>编辑</jk-button>
							</div>
							<el-dropdown>
								<jk-button type="primary" size="mini">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</jk-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										:disabled="!getPermission([`${prefix}:query`])"
									>
										<div @click="particulars(scope.row.id)">详情</div>
									</el-dropdown-item>
									<el-dropdown-item
										:disabled="!getPermission([`${prefix}:delete`]) || scope.row.auditState !== 0"
									>
										<div @click="remove(scope.row.id)">删除</div>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:dialog-state-disabled="saveDialogStateDisabled"
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, pageConfig } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import { systemUserColumnConfigGet } from '../../../../api/system/column-config';
    import {
        productionWeighingRecordTwoParentPage,
        productionWeighingRecordTwoParentDelete,
        productionWeighingRecordTwoParentUpdateAuditState,
        productionWeighingRecordTwoParentUpdateServiceState,
        productionWeighingRecordTwoParentGetReportForms
    } from '../../../../api/production/rawCotton';
    import permissionMixin from '../../../../mixins/permission-mixin';
    import { auditStateList } from '../../../../utils/jk/status-option-list';
    import Logo from '../../../../layout/components/Sidebar/Logo.vue';
    import XEUtils from 'xe-utils';

    export default {
        name: 'WeighingOrder',
        components: {
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, permissionMixin, auditStateList],
        data() {
            return {
                apiItem: {
                    'page': productionWeighingRecordTwoParentPage,
                    'delete': productionWeighingRecordTwoParentDelete,
                    'state': productionWeighingRecordTwoParentUpdateAuditState,
                    'serviceState': productionWeighingRecordTwoParentUpdateServiceState
                },
                pageType: '',
                prefix: 'production:weighingRecordTwo',
                dataId: null,
                workshopList: [],
                saveDialogStateDisabled: null,
                auditStateList: auditStateList,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                serviceState: null,
                api: null,
                overStateList: [
                    { id: 0, name: '未完成', color: '#808695' },
                    { id: 1, name: '已完成', color: '#19be6b' }
                ],
                noCalKey: ['allNum', 'allGrossWeight', 'allNetWeight', 'allTare'],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    belongDate: [],
                    selectArrivedGoodsItem: 1
                },
                recordIds: [],
                batchGroupsObject: []
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            /** 导出按钮操作 */
            onReportBtn() {
                const params = {
                    ids: this.recordIds
                };
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return productionWeighingRecordTwoParentGetReportForms(params).then(res => {
                        if (res.data.status === 200) {
                            import('@/vendor/Export2Excel').then(excel => {
                                const tHeader = ['厂批', '到货日期', '供应商', '存货编码', '存货名称', '原批', '毛重(T)', '件数', '车号', '皮重(kg)', '净重(T)', '运输单位', '付款单位', '品名'];
                                const filterVal = ['workshopBatchCode', 'belongDate', 'supplyName', 'productCode', 'productName', 'primaryBatchCode', 'grossWeight', 'num', 'carCode', 'tare', 'netWeight', 'transportName', 'payment', 'remark'];
                                const list = res.data.res ? JSON.parse(JSON.stringify(res.data.res)).map(item => {
                                    return item;
                                }) : [];
                                const data = this.insertSameNameAfterConsecutive(list).map(v => filterVal.map(j => {
                                    return v[j];
                                }));
                                excel.export_json_to_excel({
                                    header: tHeader,
                                    data,
                                    filename: `${this.$route.meta.title}`,
                                    autoWidth: true,
                                    bookType: 'xlsx'
                                });
                            });
                        }
                    });
                }).catch(() => {
                });
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `合计`;
                        }
                        if (this.noCalKey.includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            insertSameNameAfterConsecutive(data) {
                const obj = {};
                data.forEach((x, index) => {
                    if (!obj[x.primaryBatchCode]) {
                        obj[x.primaryBatchCode] = {
                            workshopBatchCode: '合计',
                            primaryBatchCode: x.primaryBatchCode,
                            idx: index,
                            num: x.allNum,
                            grossWeight: x.allGrossWeight,
                            netWeight: x.allNetWeight,
                            tare: x.allTare
                        };
                    } else {
                        obj[x.primaryBatchCode].idx = index;
                    }
                });
                // 创建一个新的数组来保存结果
                const result = [];
                // 记录每个名字最后一次出现的位置
                const lastIndices = {};
                // 遍历原数组，记录每个名字最后一次出现的位置
                data.forEach((x, index) => {
                    lastIndices[x.primaryBatchCode] = index;
                });
                // 再次遍历原数组
                data.forEach((x, index) => {
                    result.push(x); // 先把当前项添加到结果数组中
                    // 如果当前项是该名字最后一次出现
                    if (lastIndices[x.primaryBatchCode] === index) {
                        result.push(obj[x.primaryBatchCode]); // 在其后插入一个包含名字和索引的对象
                    }
                });
                return result;
            },
            onCheckBoxChange({ records }) {
                this.recordIds = [];
                records.forEach(x => {
                    this.recordIds.push(x.id);
                });
            },
            checkboxMethod(e) {
                return e.row.auditState === 1;
            },
            onItemRevocationServiceState(id) {
                this.$confirm('此操作将撤销完成该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['serviceState']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '撤销成功!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            onItemRevocationState(id) {
                this.$confirm('此操作将撤销该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['state']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '撤销成功!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            onItemServiceState(id) {
                this.$confirm('此操作将完成该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['serviceState']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '已完成!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            onItemState(id) {
                this.$confirm('此操作将完成该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['state']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '已完成!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            onStateChange(e) {
                this.saveDialogStateDisabled = e;
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'WeighingOrder', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                if (!this.searchParams.serviceState) {
                    this.$set(this.searchParams, 'serviceState', 0);
                }
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.pageType = 'detail';
                this.dataId = e.id;
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            // 详情
            particulars(id) {
                this.pageType = 'detail';
                this.dataId = id;
                this.saveDialogState = true;
            },
            // 删除
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            remove(id) {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    return this.apiItem['delete']({ id: id }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$message({
                                type: 'success',
                                message: '已删除!'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.pageType = 'add';
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row;
                this.saveDialogState = true;
            }
        }
    };
</script>
